package com.edu.yunnote;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.yunnote.dto.User;
import com.edu.yunnote.dto.WebResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //获取SharedPreferences中的用户信息
        SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
        int userId = sharedPreferences.getInt("userId", 0);//(key,若无数据需要赋的值)
        String password = sharedPreferences.getString("password", null);
        String username = sharedPreferences.getString("username", null);

        if(userId > 0 && password != null && username != null){
            String url = getString(R.string.url)+"/userServlet";
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("loginName", username);
            map.put("password", password);
            map.put("act", "login");
            try {
                postJSON(url, map , 1);
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("LOOKUP  postJSON : ", e.getMessage());
                return ;
            }
            return ;
        }

        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final Button loginButton = findViewById(R.id.login);
        final Button registerButton = findViewById(R.id.register);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
//            startActivity(intent);


            String url = getString(R.string.url)+"/userServlet";


            Map<String, Object> map = new HashMap<String, Object>();

            String loginName = usernameEditText.getText().toString().toString();
            String password = passwordEditText.getText().toString().toString();
            //Toast.makeText(LoginActivity.this,loginName + "    " + password,Toast.LENGTH_LONG).show();

            if(  "".equals(loginName) || loginName == null){
                Toast.makeText(LoginActivity.this,"用户名不能为空！",Toast.LENGTH_SHORT).show();
                return;
            }
            if(  "".equals(password) || password == null){
                Toast.makeText(LoginActivity.this,"密码不能为空！",Toast.LENGTH_SHORT).show();
                return;
            }
            map.put("loginName", loginName);
            map.put("password", password);
            map.put("act", "login");
            try {
                postJSON(url, map , 1);
            } catch (IOException e) {
                e.printStackTrace();
                Log.d("LOOKUP  postJSON : ", e.getMessage());
                return ;
            }

            }
        });

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            gotoActivity(RegisterActivity.class);
            }
        });




    }

    /**
     * intent跳转页面，不能返回之前页面
     * @param B
     */
    private void gotoActivity(Class B){
        Intent intent=new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(LoginActivity.this, B);
        startActivity(intent);
    }


    /**
     * ==============================OKHTTP请求 ==============================================
     */
    /**
     * 当前类的消息机制 手柄，句柄
     */
    private Handler handler = new Handler(new Handler.Callback() { //消息回调
        @Override
        public boolean handleMessage(Message msg) {
        Map<String, Object> parmaData = new HashMap<String, Object>();
        switch(msg.what){
            case 1:
                String res = msg.obj.toString();
                Log.d("LOOKUP -- msg.what : ", res); //请求数据在msg.obj.toString()中

                if(res.indexOf("HTTP Status") != -1){
                    Toast.makeText(LoginActivity.this,"网络请求出错" ,Toast.LENGTH_SHORT).show();
                    break;
                }

                //把json数据转换成webResponse
                WebResponse webResponse = new Gson().fromJson(res, WebResponse.class);
                Log.d("LOOKUP webResponse : ", webResponse.toString());

                if(webResponse.getStatusCode() == 200) {
                    Toast.makeText(LoginActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_LONG).show();
                    break;
                }

                //把json数据转换成map
                parmaData = new HashMap<String, Object>();
                parmaData = (Map<String, Object>) JSON.parse(JSONObject.toJSON(webResponse.getData()).toString());

                //把json数据转换成user
                User user = new Gson().fromJson(parmaData.get("user").toString(), User.class);

                //通过SharedPreference存储 保持Android登录状态记录
                SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putInt("userId",user.getUserId());
                editor.putString("username", user.getUsername());
                editor.putString("password", user.getPassword());
                editor.putString("tel", user.getTel());
                editor.commit();

                //登录成功跳到主页面
                gotoActivity(MainActivity.class);

                break;
            default:  // msg.what == 0
                Toast.makeText(LoginActivity.this,"网络服务器连接失败" ,Toast.LENGTH_SHORT).show();
                break;
        }
        return true;
        }
    });

    /**
     *
     * @param url 请求地址
     * @param map 转化成 json字符串作为请求参数
     * @param msgWhat 发送消息的编号，用于接收消息时判断
     * @return
     * @throws IOException
     */
    public void postJSON(String url , Map<String, Object> map , final Integer msgWhat) throws IOException {

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(map);
        OkHttpClient client = new OkHttpClient();
        MediaType JSON   = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call  = client.newCall(request);
        call.enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("LOOKUP","请求失败");
                Log.d("LOOKUP",e.getMessage());
                Message msg = new Message();
                msg.obj = "网络服务器连接失败";
                msg.what = 0;
                handler.sendMessage(msg);	//发送消息到句柄

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = new Message();
                msg.obj = response.body().string();
                msg.what = msgWhat;
                handler.sendMessage(msg);	//发送消息到句柄
            }
        });
    }
    /**
     * ==============================OKHTTP请求 end==============================================
     */


}
